package com.webull.information.center.carwler.job;

import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.webull.information.center.carwler.common.model.CollectRecord;
import com.webull.information.center.carwler.common.model.parm.CollectParm;
import com.webull.information.center.carwler.common.util.eljob.ElasticJobUtil;
import com.webull.information.center.carwler.dao.CollectRecordDao;
import com.webull.information.center.carwler.task.News_SinaFinanceCnStok_Task;
import com.webull.securities.client.model.Exchange;
import com.webull.securities.client.model.parm.ExchangeParam;
import com.webull.securities.client.service.ExchangeService;

/**
 * 新浪新闻采集器,针对中港美股两个交易所，定时刷新，解析任务
 * 
 * @author shimingjun
 * @date 2016年8月26日 上午10:37:10
 * @version 1.0
 * @since JDK 1.8
 */
@Component
public class News_SinaFinanceUsStok_Job implements SimpleJob {
	protected final Logger logger = LogManager.getLogger(getClass());
	private @Autowired News_SinaFinanceCnStok_Task news_SinaFinanceCnStok_Task;
	private @Autowired CollectRecordDao collectRecordDao;
	private @Autowired ExchangeService exchangeService;
	private final String collectJob = "News_SinaFinanceUsStok_Job";
	private final Integer loop = 30;// 循环20次退出,获取 20*100

	// 美的中文新闻 从新浪获取


	@Override
	public void execute(ShardingContext context) {
		int sharding = Optional.ofNullable(context).map(v -> v.getShardingItem()).orElse(-1);
		int totalCount = Optional.ofNullable(context).map(v -> v.getShardingTotalCount()).orElse(-1);
		logger.info("News_SinaFinanceUsStok_Job start:" + ArrayUtils.toString(sharding) + ",totalCount:" + totalCount);
		ExchangeParam exchangeParam = new ExchangeParam();
		exchangeParam.setRegionId(6);

		List<Exchange> exchanges = exchangeService.search(exchangeParam);
		// Collections.sort(exchanges, (c1, c2) -> ObjectUtils.compare(c1.getId(),
		// c2.getId()));

		List<Exchange> shardingExchage = Optional.ofNullable(ElasticJobUtil.shardingItems(context, exchanges))
				.orElse(exchanges);

		logger.info("News_SinaFinanceUsStok_Job div shardingRegionIds:{}; ", ArrayUtils.toString(shardingExchage));
		if (shardingExchage != null && !shardingExchage.isEmpty()) {
			process_0(shardingExchage);
		}
	}



	public void process_0(List<Exchange> exchanges) {
		Collections.shuffle(exchanges);
		logger.info("News_SinaFinanceUsStok_Job div size{};shardExchanges:{};", ArrayUtils.toString(exchanges));
		for (Exchange exchange : exchanges) {
			try {
				List<CollectRecord> records = collectRecordDao.search(collectParm(exchange));
				Integer lastId = getLastTickeId(records);
				logger.info("News_SinaFinanceUsStok_Job shardExchanges start collectJob{} div ,reginoId:{},lastId{}",
						collectJob, exchange, lastId);
				Integer lastId_ = news_SinaFinanceCnStok_Task.fullSinaStockFinanceNewsEx(exchange.getExchangeCode(), -1,
						null);
				CollectRecord record = backRecord(exchange);
				record.setLastTickerId(lastId_);
				Integer collId = collectRecordDao.add(record);
				logger.info("News_SinaFinanceUsStok_Job shardExchanges end collectJob{} div ,reginoId:{},collId{}",
						collectJob, exchange, collId);
			} catch (Exception e) {
				logger.error("News_SinaFinanceUsStok_Job shardExchanges collectJob div error:" + exchange, e);
			}
		}
	}

	private Integer getLastTickeId(List<CollectRecord> records) {
		if (records == null || records.isEmpty()) {
			return -1;
		} else {
			return records.get(0).getLastTickerId();
		}
	}

	private CollectParm collectParm(Exchange exchage0) {
		CollectParm parm = new CollectParm();
		parm.setCollectJob(collectJob);
		parm.setExchangeCode(exchage0.getExchangeCode());
		parm.setExchangeId(exchage0.getId());
		parm.setRecordType(CollectRecord.RecordTypeConstants.NEWS_SINA);
		return parm;
	}

	private CollectRecord backRecord(Exchange exchage0) {
		CollectRecord record = new CollectRecord();
		record.setCollectJob(collectJob);
		record.setExchangeCode(exchage0.getExchangeCode());
		record.setExchangeId(exchage0.getId());
		record.setRecordType(CollectRecord.RecordTypeConstants.NEWS_SINA);
		try {
			record.setCustomer(InetAddress.getLocalHost().getHostAddress());
		} catch (Exception e) {
		}
		return record;
	}

}
